﻿using System;

using System.Collections;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Global.Class.Library;
using BusinessLogicLayer;
using DataAccessLayer;
using DataTransferObject;

using System.Globalization;
using BrightIdeasSoftware;
using Equin.ApplicationFramework;

namespace PresentationLayer
{
    public partial class GCGBWHOutput : Form, IMergeToolStrip, ICallToolStrip
    {

        #region <Implement Interface>

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public GlobalEnum.TaskID TaskID
        {
            get { return this.gcgbWHOutputBLL.TaskID; }
        }


        public ToolStrip ChildToolStrip
        {
            get
            {
                return this.toolStripChildForm;
            }
            set
            {
                this.toolStripChildForm = value;
            }
        }
        
        #region Context toolbar


        public bool IsDirty
        {
            get { return this.gcgbWHOutputBLL.IsDirty; }
        }

        public bool IsValid
        {
            get { return this.gcgbWHOutputBLL.IsValid; }
        }

        public bool Closable
        {
            get { return true; }
        }

        public bool Loadable
        {
            get { return true; }
        }

        public bool Newable
        {
            get { return !this.gcgbWHOutputBLL.ReadOnly; }            
        }

        public bool Editable
        {
            get { return this.gcgbWHOutputBLL.Editable; }            
        }

        public bool Deletable
        {
            get { return this.gcgbWHOutputBLL.Editable; }            
        }

        public bool Importable
        {
            get { return false; }
        }

        public bool Exportable
        {
            get { return false; }
        }

        public bool Verifiable
        {
            get { return this.gcgbWHOutputBLL.Verifiable; }
        }

        public bool Unverifiable
        {
            get { return this.gcgbWHOutputBLL.Unverifiable; }
        }

        public bool Printable
        {
            get { return false; }
        }

        public bool Searchable
        {
            get { return true; }
        }


        /// <summary>
        /// Edit Mode: True, Read Mode: False
        /// </summary>
        private bool editableMode;
        private int lastGCGBWHOutputID;
        public bool EditableMode { get { return this.editableMode; } }
        /// <summary>
        /// This reverse of the EditableMode
        /// </summary>
        public bool ReadonlyMode { get { return !this.editableMode; } }

        /// <summary>
        /// Set the editableMode
        /// </summary>
        /// <param name="editableMode"></param>
        private void SetEditableMode(bool editableMode)
        {
            if (this.editableMode != editableMode)
            {
                this.lastGCGBWHOutputID = this.gcgbWHOutputBLL.GCGBWHOutputID;
                this.editableMode = editableMode;
                this.NotifyPropertyChanged("EditableMode");
            }
        }


        private void CancelDirty(bool restoreSavedData)
        {
            try
            {
                if (restoreSavedData || this.gcgbWHOutputBLL.GCGBWHOutputID <= 0)
                    this.gcgbWHOutputBLL.Fill(this.lastGCGBWHOutputID);

                this.SetEditableMode(false);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }



        #endregion Context toolbar



        #region ICallToolStrip

        public void Escape()
        {
            if (this.EditableMode)
            {
                if (this.IsDirty)
                {
                    DialogResult dialogResult = MessageBox.Show(this, "Do you want to save your change?", "Warning", MessageBoxButtons.YesNoCancel);
                    if (dialogResult == DialogResult.Yes)
                    {
                        this.Save();
                        if (!this.IsDirty) this.CancelDirty(false);
                    }
                    else if (dialogResult == DialogResult.No)
                    {
                        this.CancelDirty(true);
                    }
                    else
                        return;
                }
                else
                    this.CancelDirty(false);
            }
            else
                this.Close(); //Unload this module
        }

        //Can phai xem lai trong VB de xem lai this.SetEditableMode () khi can thiet

        public void Loading()
        {
            this.GetMasterList();
        }

        public void New()
        {
            this.SetEditableMode(true);
            this.gcgbWHOutputBLL.New();
            pictureBoxWizard_Click(this, new EventArgs());
        }

        public void Edit()
        {
            this.SetEditableMode(true);
            this.gcgbWHOutputBLL.Edit();
        }

        public void Save()
        {
            this.gcgbWHOutputBLL.Save();
            this.GetMasterList();
        }

        public void Delete()
        {
            this.gcgbWHOutputBLL.Delete();
            this.GetMasterList();
        }

        public void Import()
        {
        }

        public void Export()
        {
            MessageBox.Show("Export");
        }

        public void Verify()
        {
            MessageBox.Show("Verify");
        }

        public void Print(PrintDestination printDestination)
        {
            MessageBox.Show("Print");
        }

        public void SearchText(string searchText)
        {
            CommonFormAction.OLVFilter(this.dataListViewMaster, searchText);
        }

        #endregion


        #endregion <Implement Interface>
        
        #region <Storage>

        private const int colQuantity = 3;

        private GCGBWHOutputBLL gcgbWHOutputBLL;

        #endregion <Storage>


        public GCGBWHOutput()
        {
            try
            {
                InitializeComponent();

                this.gcgbWHOutputBLL = new GCGBWHOutputBLL();

                this.gcgbWHOutputBLL.PropertyChanged += new PropertyChangedEventHandler(gcgbWHOutputBLL_PropertyChanged);                

            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        void gcgbWHOutputBLL_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            this.NotifyPropertyChanged(e.PropertyName);
        }


        private void GCGBWHOutput_Load(object sender, EventArgs e)
        {
            try
            {
                InitializeCommonControlBinding();

                InitializeDataGridBinding();

                InitializeReadOnlyModeBinding();
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }


        #region <InitializeBinding>

        Binding gcgbCommandReferenceAndDateBinding;
        Binding preparedEmployeeIDBinding;        
        Binding approvedEmployeeIDBinding;

        Binding gcgbWHOutputReferenceBinding;
        Binding gcgbWHOutputDateBinding;

        Binding stockMaterialIDBidnding;

        Binding entryDateBinding;

        Binding remarksBinding;

        Binding isDirtyBinding;
        Binding isDirtyBLLBinding;

        private void InitializeCommonControlBinding()
        {
            CommonMetaList commonMetaList = new CommonMetaList();

            ERmgrVCP.ListStockMaterialNameDataTable listStockMaterialNameDataTable = commonMetaList.GetStockMaterialName();
            this.comboBoxStockMaterialID.DataSource = listStockMaterialNameDataTable;
            this.comboBoxStockMaterialID.DisplayMember = listStockMaterialNameDataTable.DescriptionOfficialColumn.ColumnName;
            this.comboBoxStockMaterialID.ValueMember = listStockMaterialNameDataTable.StockMaterialIDColumn.ColumnName;
            this.stockMaterialIDBidnding = this.comboBoxStockMaterialID.DataBindings.Add("SelectedValue", this.gcgbWHOutputBLL.GCGBWHOutputMaster, "StockMaterialID", true);

            ERmgrVCP.ListEmployeeMasterDataTable listEmployeeMasterDataTable = commonMetaList.GetEmployeeMaster();
            this.comboBoxPreparedEmployeeID.DataSource = listEmployeeMasterDataTable;
            this.comboBoxPreparedEmployeeID.DisplayMember = listEmployeeMasterDataTable.FullNameColumn.ColumnName;
            this.comboBoxPreparedEmployeeID.ValueMember = listEmployeeMasterDataTable.EmployeeIDColumn.ColumnName;
            this.preparedEmployeeIDBinding = this.comboBoxPreparedEmployeeID.DataBindings.Add("SelectedValue", this.gcgbWHOutputBLL.GCGBWHOutputMaster, "PreparedEmployeeID", true);

            listEmployeeMasterDataTable = (ERmgrVCP.ListEmployeeMasterDataTable)listEmployeeMasterDataTable.Copy();
            this.comboBoxApprovedEmployeeID.DataSource = listEmployeeMasterDataTable;
            this.comboBoxApprovedEmployeeID.DisplayMember = listEmployeeMasterDataTable.FullNameColumn.ColumnName;
            this.comboBoxApprovedEmployeeID.ValueMember = listEmployeeMasterDataTable.EmployeeIDColumn.ColumnName;
            this.approvedEmployeeIDBinding = this.comboBoxApprovedEmployeeID.DataBindings.Add("SelectedValue", this.gcgbWHOutputBLL.GCGBWHOutputMaster, "ApprovedEmployeeID", true);


            this.gcgbCommandReferenceAndDateBinding = this.textBoxGCGBCommandReferenceAndDate.DataBindings.Add("Text", this.gcgbWHOutputBLL.GCGBWHOutputMaster, "GCGBCommandReferenceAndDate", true);

            this.gcgbWHOutputReferenceBinding = this.textBoxGCGBWHOutputReference.DataBindings.Add("Text", this.gcgbWHOutputBLL.GCGBWHOutputMaster, "GCGBWHOutputReference", true);

            this.gcgbWHOutputDateBinding = this.dateTimePickerGCGBWHOutputDate.DataBindings.Add("Value", this.gcgbWHOutputBLL.GCGBWHOutputMaster, "GCGBWHOutputDate", true);
            this.entryDateBinding = this.dateTimePickerEntryDate.DataBindings.Add("Value", this.gcgbWHOutputBLL.GCGBWHOutputMaster, "EntryDate", true);

            this.remarksBinding = this.textBoxRemarks.DataBindings.Add("Text", this.gcgbWHOutputBLL.GCGBWHOutputMaster, "Remarks", true);

            this.isDirtyBinding = this.checkBoxIsDirty.DataBindings.Add("Checked", this.gcgbWHOutputBLL.GCGBWHOutputMaster, "IsDirty", true);
            this.isDirtyBLLBinding = this.checkBoxIsDirtyBLL.DataBindings.Add("Checked", this.gcgbWHOutputBLL, "IsDirty", true);

            this.textBoxTotalQuantity.DataBindings.Add("Text", this.gcgbWHOutputBLL, "TotalQuantity", true);
            this.textBoxTotalQuantitySemi1.DataBindings.Add("Text", this.gcgbWHOutputBLL, "TotalQuantitySemi1", true);
            this.textBoxTotalQuantitySemi2.DataBindings.Add("Text", this.gcgbWHOutputBLL, "TotalQuantitySemi2", true);
            this.textBoxTotalQuantitySemi3.DataBindings.Add("Text", this.gcgbWHOutputBLL, "TotalQuantitySemi3", true);

            this.gcgbCommandReferenceAndDateBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);

            this.preparedEmployeeIDBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);            
            this.approvedEmployeeIDBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);

            this.remarksBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.stockMaterialIDBidnding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);

            this.gcgbWHOutputDateBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.gcgbWHOutputDateBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);            

            this.isDirtyBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.isDirtyBLLBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);


            this.filterTextBox.DataBindings.Add("Visible", this, "EditableMode", true, DataSourceUpdateMode.OnPropertyChanged);
            this.naviGroupDetails.DataBindings.Add("ExpandedHeight", this.numericUpDownSizingDetail, "Value", true, DataSourceUpdateMode.OnPropertyChanged);
            this.numericUpDownSizingDetail.Minimum = this.naviGroupDetails.HeaderHeight * 2;
            this.numericUpDownSizingDetail.Maximum = this.naviGroupDetails.Height + this.dataListViewMaster.Height;

            this.tableLayoutPanelMaster.ColumnStyles[this.tableLayoutPanelMaster.ColumnCount - 1].SizeType = SizeType.Absolute; this.tableLayoutPanelMaster.ColumnStyles[this.tableLayoutPanelMaster.ColumnCount - 1].Width = 10;
            this.tableLayoutPanelExtend.ColumnStyles[this.tableLayoutPanelExtend.ColumnCount - 1].SizeType = SizeType.Absolute; this.tableLayoutPanelExtend.ColumnStyles[this.tableLayoutPanelExtend.ColumnCount - 1].Width = 10;

            this.errorProviderMaster.DataSource = this.gcgbWHOutputBLL.GCGBWHOutputMaster;
           
        }

        private void CommonControl_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            if (e.BindingCompleteState == BindingCompleteState.Exception) { GlobalExceptionHandler.ShowExceptionMessageBox(this, e.ErrorText); e.Cancel = true; }
        }

        private void numericUpDownSizingDetail_ValueChanged(object sender, EventArgs e)
        {
            this.naviGroupDetails.Expand();
        }

        private void naviGroupDetails_HeaderMouseClick(object sender, MouseEventArgs e)
        {
            this.numericUpDownSizingDetail.Visible = this.naviGroupDetails.Expanded;
            this.toolStripNaviGroupDetails.Visible = this.naviGroupDetails.Expanded;
        }

        private void toolStripButtonShowDetailsExtend_Click(object sender, EventArgs e)
        {
            this.naviGroupDetailsExtend.Expanded = !this.naviGroupDetailsExtend.Expanded;
            this.toolStripButtonShowDetailsExtend.Image = this.naviGroupDetailsExtend.Expanded ? ResourceIcon.Chevron_Collapse.ToBitmap() : ResourceIcon.Chevron_Expand.ToBitmap();
        }




        private void GetMasterList()
        {
            this.dataListViewMaster.SetNativeBackgroundTiledImage(global::PresentationLayer.Properties.Resources.Background2);

            foreach (OLVColumn olvColumn in dataListViewMaster.Columns) { olvColumn.Renderer = null; }

            DataTable gcgbWHOutputMasterList = this.gcgbWHOutputBLL.GCGBWHOutputListing(GlobalVariables.GlobalOptionSetting.LowerFillterDate, GlobalVariables.GlobalOptionSetting.UpperFillterDate);
            gcgbWHOutputMasterList.TableName = "GCGBWHOutputListing";

            DataSet bindingDataSet = new DataSet();
            bindingDataSet.Tables.Add(gcgbWHOutputMasterList);

            this.dataListViewMaster.AutoGenerateColumns = false;
            this.dataListViewMaster.DataSource = gcgbWHOutputMasterList;
        }

        private void InitializeDataGridBinding()
        {

            this.GetMasterList();

            #region <dataGridViewDetail>

            CommonMetaList commonMetaList = new CommonMetaList();          

            this.dataGridViewGCGBWHOutputCollection.AutoGenerateColumns = false;
            gcgbWHOutputCollectionListView = new BindingListView<GCGBWHOutputCollection>(this.gcgbWHOutputBLL.GCGBWHOutputCollectionList);
            this.dataGridViewGCGBWHOutputCollection.DataSource = gcgbWHOutputCollectionListView;

            DataGridViewComboBoxColumn comboBoxColumn;

            ERmgrVCP.ListMaterialSetNameDataTable listMaterialSetNameDataTable = commonMetaList.GetMaterialSetName(true);
            comboBoxColumn = (DataGridViewComboBoxColumn)this.dataGridViewGCGBWHOutputCollection.Columns[listMaterialSetNameDataTable.MaterialSetIDColumn.ColumnName];
            comboBoxColumn.DataSource = listMaterialSetNameDataTable;
            comboBoxColumn.DisplayMember = listMaterialSetNameDataTable.DescriptionColumn.ColumnName;
            comboBoxColumn.ValueMember = listMaterialSetNameDataTable.MaterialSetIDColumn.ColumnName;


            ERmgrVCP.ListMaterialSemiNameDataTable listMaterialSemiDataTable = commonMetaList.GetMaterialSemiName(true);
            comboBoxColumn = (DataGridViewComboBoxColumn)this.dataGridViewGCGBWHOutputCollection.Columns["MaterialSemiID1"];
            comboBoxColumn.DataSource = listMaterialSemiDataTable;
            comboBoxColumn.DisplayMember = listMaterialSemiDataTable.DescriptionColumn.ColumnName;
            comboBoxColumn.ValueMember = listMaterialSemiDataTable.MaterialSemiIDColumn.ColumnName;

            comboBoxColumn = (DataGridViewComboBoxColumn)this.dataGridViewGCGBWHOutputCollection.Columns["MaterialSemiID2"];
            comboBoxColumn.DataSource = listMaterialSemiDataTable;
            comboBoxColumn.DisplayMember = listMaterialSemiDataTable.DescriptionColumn.ColumnName;
            comboBoxColumn.ValueMember = listMaterialSemiDataTable.MaterialSemiIDColumn.ColumnName;

            comboBoxColumn = (DataGridViewComboBoxColumn)this.dataGridViewGCGBWHOutputCollection.Columns["MaterialSemiID3"];
            comboBoxColumn.DataSource = listMaterialSemiDataTable;
            comboBoxColumn.DisplayMember = listMaterialSemiDataTable.DescriptionColumn.ColumnName;
            comboBoxColumn.ValueMember = listMaterialSemiDataTable.MaterialSemiIDColumn.ColumnName;

            StackedHeaderDecorator stackedHeaderDecorator = new StackedHeaderDecorator(this.dataGridViewGCGBWHOutputCollection);

            this.dataGridViewGCGBWHOutputCollection.ColumnWidthChanged += new DataGridViewColumnEventHandler(dataGridViewGCGBWHOutputCollection_ColumnWidthChanged);

            #endregion <dataGridViewDetail>
        }        


        private void InitializeReadOnlyModeBinding()
        {
            List<Control> controlList = GlobalStaticFunction.GetAllControls(this);

            foreach (Control control in controlList)
            {
                //if (control is TextBox) control.DataBindings.Add("Readonly", this, "ReadonlyMode");
                if (control is TextBox) control.DataBindings.Add("Enabled", this, "EditableMode");
                else if (control is ComboBox || control is DateTimePicker) control.DataBindings.Add("Enabled", this, "EditableMode");
                else if (control is DataGridView)
                {    
                    //control.DataBindings.Add("Readonly", this, "ReadonlyMode");
                    ////control.DataBindings.Add("AllowUserToAddRows", this, "EditableMode");
                    //control.DataBindings.Add("AllowUserToDeleteRows", this, "EditableMode");
                }
            }

            this.dataListViewMaster.DataBindings.Add("Enabled", this, "ReadonlyMode");
        }

        #endregion <InitializeBinding>


        private void dataGridViewGCGBWHOutputCollection_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            int X1 = this.dataGridViewGCGBWHOutputCollection.GetCellDisplayRectangle(this.dataGridViewGCGBWHOutputCollection.Columns["Quantity"].Index, -1, true).Location.X;
            int X2 = this.dataGridViewGCGBWHOutputCollection.GetCellDisplayRectangle(this.dataGridViewGCGBWHOutputCollection.Columns["QuantitySemi1"].Index, -1, true).Location.X;
            int X3 = this.dataGridViewGCGBWHOutputCollection.GetCellDisplayRectangle(this.dataGridViewGCGBWHOutputCollection.Columns["QuantitySemi2"].Index, -1, true).Location.X;
            int X4 = this.dataGridViewGCGBWHOutputCollection.GetCellDisplayRectangle(this.dataGridViewGCGBWHOutputCollection.Columns["QuantitySemi3"].Index, -1, true).Location.X;

            int Y = this.textBoxTotalQuantity.Location.Y;

            this.textBoxTotalQuantity.Width = this.dataGridViewGCGBWHOutputCollection.Columns["Quantity"].Width;
            this.textBoxTotalQuantity.Location = new Point(X1, Y);

            this.textBoxTotalQuantitySemi1.Width = this.dataGridViewGCGBWHOutputCollection.Columns["QuantitySemi1"].Width;
            this.textBoxTotalQuantitySemi1.Location = new Point(X2, Y);

            this.textBoxTotalQuantitySemi2.Width = this.dataGridViewGCGBWHOutputCollection.Columns["QuantitySemi2"].Width;
            this.textBoxTotalQuantitySemi2.Location = new Point(X3, Y);

            this.textBoxTotalQuantitySemi3.Width = this.dataGridViewGCGBWHOutputCollection.Columns["QuantitySemi3"].Width;
            this.textBoxTotalQuantitySemi3.Location = new Point(X4, Y);
        }

        private void dataListViewMaster_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ObjectListView objectListView = (ObjectListView)sender;
                DataRowView row = (DataRowView)objectListView.SelectedObject;

                if (row != null)
                {
                    int gcgbWHOutputID;

                    if (int.TryParse(row.Row["GCGBWHOutputID"].ToString(), out gcgbWHOutputID)) this.gcgbWHOutputBLL.Fill(gcgbWHOutputID);
                    else this.gcgbWHOutputBLL.Fill(-1);
                }
                else this.gcgbWHOutputBLL.Fill(-1);
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }      


        private void dataGridViewThanhLyDetail_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridViewGCGBWHOutputCollection.SelectedCells.Count >= 1)
                {
                    List<int> listOfSelectedRow = new List<int>();
                    for (int i = 0; (i < this.dataGridViewGCGBWHOutputCollection.SelectedCells.Count); i++)
                    {
                        if (this.dataGridViewGCGBWHOutputCollection.SelectedCells[i].ColumnIndex == colQuantity)
                            listOfSelectedRow.Add(this.dataGridViewGCGBWHOutputCollection.SelectedCells[i].RowIndex);
                    }

                    this.DoGCGBWHOutputAutomatically(listOfSelectedRow);
                }
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private void DoGCGBWHOutputAutomatically(List<int> listOfSelectedRow)
        {
            if (this.EditableMode)
            {
                for (int i = 0; i < listOfSelectedRow.Count; i++)
                {
                    GCGBWHOutputCollection gcgbWHOutputCollection = ((ObjectView<GCGBWHOutputCollection>)this.dataGridViewGCGBWHOutputCollection.Rows[listOfSelectedRow[i]].DataBoundItem).Object as GCGBWHOutputCollection;
                    if (gcgbWHOutputCollection != null && gcgbWHOutputCollection.Quantity == 0) gcgbWHOutputCollection.Quantity = (int)gcgbWHOutputCollection.RemainsQuantity;
                }
            }
        }

        BindingListView<GCGBWHOutputCollection> gcgbWHOutputCollectionListView;
        private void filterTextBox_TextChanged(object sender, EventArgs e)
        {// Change the filter of the view.
            gcgbWHOutputCollectionListView.ApplyFilter(
                delegate(GCGBWHOutputCollection gcgbWHOutputCollection)
                {
                    // uses ToLower() to ignore case of text.
                    return gcgbWHOutputCollection.Remarks.ToLower().Contains(filterTextBox.Text.ToLower());
                }
            );


        }

        private void filterTextBox_VisibleChanged(object sender, EventArgs e)
        {
            this.filterTextBox.Clear();
        }

        private void pictureBoxWizard_Click(object sender, EventArgs e)
        {
            if (this.EditableMode)
            {
                WizardGCGBWHOutputNew wizardGCGBWHOutputNew = new WizardGCGBWHOutputNew(this.gcgbWHOutputBLL.GCGBWHOutputMaster);
                wizardGCGBWHOutputNew.ShowDialog(this);
                this.gcgbCommandReferenceAndDateBinding.ReadValue();
            }
        }

        private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }        

        
    }

}
